package com.bemyapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.bemyapp.model.Extract;
import com.bemyapp.mp.MP;
import com.bemyapp.tts.ParrotTTSObserver;
import com.bemyapp.tts.ParrotTTSPlayer;

public class RepeatActivity extends Activity implements ParrotTTSObserver, OnCompletionListener{
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	Extract e;
	TextView tvEnglish;
	ParrotTTSPlayer pttsPlayer;
	DBAdapter db;
	int compteur;
	int state ; // 0 not started
				// 1 Asking for repeat
				// 2 waitin for answer & say "Bravo" !
				// 3 traduction
	
	
	Handler handler;
	private AsyncTask<Void, Void, Void> currentAsync;
	private WakeLock wl;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.handler = new Handler();
		
		setContentView(R.layout.repeat);
		tvEnglish = (TextView)findViewById(R.id.textRepeatEnglish);

		db = new DBAdapter(this);
		db.open();
		MP.getInstance().setOnCompletionListener(this);
		
		PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "whereisbryan");
        System.out.println("wake lock ============ create");
        wl.acquire();
		
	}

	void getExtractAndAskRepeat(){
		state = 1;

		e = db.getExtractToRepeat(false);

		handler.post(new Runnable() {
			
			@Override
			public void run() {
				findViewById(R.id.layoutRepeat).setBackgroundResource(e.isRepeatDone() ? R.drawable.deja_fait : R.drawable.pas_fait);
				tvEnglish.setText(e.getEnglish());
			}
		});
		
		
		this.currentAsync = new AsyncTask<Void, Void, Void>(){
			protected Void doInBackground(Void... params) {
				long timer = System.currentTimeMillis();
				do{}while(System.currentTimeMillis()-timer < 1000);
				return null;
			}
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				pttsPlayer.play("Répétez. ");
			}
		};
		this.currentAsync.execute();
	}
	
	public void getRealEnglish(){
		state = 2;
		e.playEnglish(this);
	}
	
	
	void waitForAnswer(){
		state=3;
		
		this.currentAsync = new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... params) {
				long timer = System.currentTimeMillis();
				do{}while(System.currentTimeMillis()-timer < 3000);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				pttsPlayer.play("Bravo ! ");
				e.setRepeatDone(true);
				db.extractIsAlreadyRepeated(e.getId());
			}
		};
		this.currentAsync.execute();

	}	
	
	void getTraduction(){
		state=4;
		
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				tvEnglish.setText(e.getFrench());
			}
		});

		this.currentAsync = new AsyncTask<Void, Void, Void>(){
			protected Void doInBackground(Void... params) {
				long timer = System.currentTimeMillis();
				do{}while(System.currentTimeMillis()-timer < 1000);
				return null;
			}
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				compteur++;
				pttsPlayer.play("La traduction et");
				pttsPlayer.play(e.getFrench());
			}
		};
		this.currentAsync.execute();

	}	
	
	@Override
	public void onTTSFinished() {
		if (currentAsync.isCancelled()) return;
		
		if(compteur == 3){
			
		       final Intent intent = new Intent(PopupActivity.class.getName());
		       intent.putExtra(PopupActivity.POPUP_TEXT, "Voulez vous tenter une traduction ?");
		       intent.putExtra(PopupActivity.POPUP_LENGTH, PopupActivity.SHORT);
		       intent.putExtra(PopupActivity.VALID_CALLBACK_ACTION, "com.bemyapp.PopupActivity");
		       startActivity(intent);

			return;
		}
		if 		(state ==1) this.getRealEnglish();
		else if	(state ==2)	waitForAnswer();
		else if (state ==3) getTraduction();
		else if (state ==4) getExtractAndAskRepeat();
		
	}	
	
	   @Override
	   protected void onNewIntent(Intent intent) {
			if (wl == null){
				PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
		        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "whereisbryan");
		        System.out.println("wake lock ============ onNewIntent");
		        wl.acquire();
			}
		   
	       //the ok button of pop up has been validated
	       if ("com.bemyapp.PopupActivity".equals(intent.getAction())){
	    		Intent i = new Intent(this,TranslationActivity.class) ;
	    		i.putExtra("repeat", true);
	    		this.startActivity(i);
	    		this.finish();
	       } else {
	           super.onNewIntent(intent);
	       }
	   }
	

	@Override
	public void onTTSAborted() {
		Log.d("DEBUGTAG","Le TTS a été aborted");
		Toast.makeText(this, "Un problème vient d'arriver, veuillez relancer l'exercice de répétition", Toast.LENGTH_LONG).show();
	}
	
	protected void onResume(){
		super.onResume();
		pttsPlayer = new ParrotTTSPlayer(this, this);
		compteur=0;
		state = 0;
		try {
			db.open();
		} catch (Exception e){
			
		}
		
		if (wl == null){
			PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
	        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "whereisbryan");
	        System.out.println("wake lock ============ resume");
	        wl.acquire();
		}
		
		MP.getInstance().setOnCompletionListener(this);
		this.getExtractAndAskRepeat();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_DPAD_UP) 
			MP.volumeDown(this, AudioManager.STREAM_MUSIC);
		else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) 
			MP.volumeUp(this, AudioManager.STREAM_MUSIC);
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		this.currentAsync.cancel(true);
		try {
			MP.getInstance().stop();
		}catch(Exception e){
			
		}
		pttsPlayer.destroy();
		if (wl != null) {
			wl.release();
			System.out.println("wake lock ============ pause");
			wl = null;
		}
	}
	@Override
	protected void onStop() {
		super.onStop();
		db.close();
		if (wl != null){
			wl.release();
			System.out.println("wake lock ============ stop");
			wl = null;
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		this.onTTSFinished();
	}
}
